<?php

namespace App\Http\Middleware\Auth;

use App\Http\Services\LoginService;
use App\Models\User\User;
use Closure;


class ShopLogin
{
    /**
     * 小程序登录验证
     */
    public function handle($request, Closure $next)
    {
        $token = $request->header('shopToken');

        if (empty($token)) {
            return response([
                'code' => 401,
                'msg' => '权限不足',
                'data' => []
            ], 401);
        }

        $login = new LoginService();
        $adminId = $login->authcode($token, 'DECODE');
        if (empty($adminId)) {
            return response([
                'code' => 401,
                'msg' => '无效的Token',
                'data' => []
            ], 401);
        }

        if ($adminId) {
            define("UID", $adminId);
        } else {
            define("UID", 0);
        }

        $shop_id = User::query()->where("id", UID)->value("shop_id");
        define("SHOP_ID", $shop_id ?? '');

        return $next($request);
    }
}
